import axios from "axios";
import { Notify } from "vant";
import { filterData } from "./specialData";
import { handleData } from "../utils/handleData";
import { getRandomString } from "@/plugins/utils/common";
import Setting from "../../setting";

// axios.defaults.withCredentials = true; // 允许跨域携带cookie信息
// 创建一个 axios 实例
const service = axios.create({
  baseURL: Setting.apiBaseURLDic,
  widthCredentials: true,
  crossDomain: true,
  timeout: 30000, // 请求超时时间
});
function geturlparam(url) {
  if (!url) return;
  let p = url.split("?")[1];
  return p;
}

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (Setting.codeMode === "uapRelease") {
      config.baseURL = config.baseURL.replace('/frameworkPre', sessionStorage.getItem("UAP_ISC_PORT") + '/api/ps/framework');
    } else if (Setting.codeMode === "norRelease") {
      config.baseURL = config.baseURL.replace('/frameworkPre', '/api/ps/framework');
    }
    let sign = ""; let str = ""; let salt = getRandomString();
    if (config.data && config.method != "get") {
      if (config.url.indexOf("?") > -1) { str = decodeURI(geturlparam(config.url)); }
      let obj = {};
      if (config.data instanceof FormData) { // 表单提交
        let hasFile = false;
        for (var [key, value] of config.data) {
          if (value instanceof File) {
            hasFile = true;
            obj.file = value.fileName;
          } else { obj[key] = value; }
        }
        if (hasFile) {
          let arr = Object.keys(obj).sort(); let sortObj = {};
          arr.forEach((item) => { sortObj[item] = obj[item]; });
          str += JSON.stringify(sortObj) + salt;
        } else {
          str += decodeURI(JSON.stringify(obj)) + salt;
        }
      } else if (config.data instanceof Array) { // data值为数组
        str += JSON.stringify(config.data) + salt;
      } else {
        for (var key in config.data) {
          if (config.data[key] instanceof File) { } else { obj[key] = config.data[key]; }
        }
        str += JSON.stringify(obj) + salt;
      }
    } else if (config.url.indexOf("?") > -1) {
      str = decodeURI(geturlparam(config.url)) + salt;
    } else if (config.params) {
      for(let key in config.params) { str += key + "=" + config.params[key] + "&"; }
      str = str ? (decodeURI(str.slice(0, -1)) + salt) : salt;
    } else { str = salt; }
    sign = SG_sm3encrypt(str);
    config.headers["sign"] = sign;
    config.headers["salt"] = salt;
    // 在请求发送之前做一些处理
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    // config.headers['X-Token'] = token;
    config.headers["igw-env"] = Setting.igwEnv; // i国网环境标识
    let token = sessionStorage.getItem("token") || "";
    let userid = sessionStorage.getItem("userid") || "";
    config.headers["token"] = token;
    config.headers["userid"] = userid;
    return config;
  },
  (error) => {
    // 发送失败
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (Setting.isFilterSpecialCharacters && filterData(response.data)) {
      return false;
    } else {
      const token = response.headers.token || "";
      const prevToken = sessionStorage.getItem("token") || "";
      if (!prevToken) {
        sessionStorage.setItem("token", token);
      }
      const dataAxios = response.data;
      return handleData(dataAxios, response.config.url);
    }
  },
  (error) => {
    sessionStorage.removeItem("statusCode");
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "请求错误";
          break;
        case 401:
          error.message = "未授权，请登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = `请求地址出错`;
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "服务器内部错误";
          break;
        case 501:
          error.message = "服务未实现";
          break;
        case 502:
          error.message = "网关错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "网关超时";
          break;
        case 505:
          error.message = "HTTP版本不受支持";
          break;
        default:
          break;
      }
      if (error.message) {
        Notify({ type: "warning", message: error.message });
      }
    } else {
      if (error.code === "ECONNABORTED" || error.message.includes("timeout")) {
        Notify({ type: "warning", message: "当前网络状态不佳" });
      }
    }
    return Promise.reject(error);
  }
);
export default service;
